package main

import (
	"io/ioutil"
	"log"
	"net/http"
	_ "net/http/pprof"
	"os"
)

// WebHandler web接口的回调类型
type WebHandler func(writer http.ResponseWriter, request *http.Request)

// ErrHandle 对回调函数进行包裹的函数
func ErrHandle(handler WebHandler) WebHandler {
	return func(writer http.ResponseWriter, request *http.Request) {
		defer func() {
			r := recover()
			if r != nil {
				switch r.(type) {
				case error:
					http.Error(writer, r.(error).Error(), http.StatusBadRequest)
				default:
					http.Error(writer, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
				}
			}
		}()
		log.Println(request.URL.Path)
		handler(writer, request)
		log.Println(request.URL.Path, "[[ 处理结束! ]]")
	}
}

func listHandle(writer http.ResponseWriter, request *http.Request) {
	s := request.URL.Path[len("/list/"):]

	f, err := os.OpenFile(s, os.O_RDONLY, 0666)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	content, err := ioutil.ReadAll(f)
	if err != nil {
		panic(err)
	}
	_, err = writer.Write(content)
	if err != nil {
		panic(err)
	}
}

// 测试调用函数
func main() {
	http.HandleFunc("/list/", ErrHandle(listHandle))

	http.ListenAndServe("0.0.0.0:8080", nil)
}
